/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sv.edu.ugb.vistacontrolador.beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import sv.edu.ugb.modelo.dto.AlumnosDTO;

/**
 *
 * @author xtecuan
 */
@Stateless
public class BusquedaBean {

    @Resource(name = "dataSource")
    private DataSource dataSource;
    private static final Logger logger = Logger.getLogger(BusquedaBean.class);

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public java.util.List<sv.edu.ugb.modelo.dto.AlumnosDTO> buscarAlumnoPorNombresLike(String nombreLike) {

        Connection conn = null;
        PreparedStatement psta = null;
        List<AlumnosDTO> respuesta = new ArrayList<AlumnosDTO>(0);



        try {

            conn = dataSource.getConnection();

            psta = conn.prepareStatement(AlumnosDTO.getSELECT_LIKE_NOMBRES());

            psta.setString(1, "%" + nombreLike + "%");

            ResultSet rset = psta.executeQuery();


            while (rset.next()) {

                AlumnosDTO dto = new AlumnosDTO();

                Integer id = rset.getInt("id");
                dto.setId(id);
                String login = rset.getString("login");
                dto.setLogin(login);
                String password = rset.getString("password");
                dto.setPassword(password);
                

                respuesta.add(dto);


            }

            rset.close();
            psta.close();


        } catch (Exception e) {

            logger.error("Error al buscar alumnos por nombre like: ", e);
        } finally {
            try {

                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ex) {
                logger.error("Error al cerrar la conexion !!!", ex);
            }
        }


        return respuesta;
    }

    public java.util.List<sv.edu.ugb.modelo.dto.AlumnosDTO> listarAlumnos() {
        Connection conn = null;
        PreparedStatement psta = null;
        List<AlumnosDTO> respuesta = new ArrayList<AlumnosDTO>(0);
        
        try {
            conn = dataSource.getConnection();
            psta = conn.prepareStatement(AlumnosDTO.getSELECT_ALL());            
            ResultSet rset = psta.executeQuery();
          
            while(rset.next()){
                AlumnosDTO dto = new AlumnosDTO();

                Integer id = rset.getInt("id");
                dto.setId(id);
                String login = rset.getString("login");
                dto.setLogin(login);
                String password = rset.getString("password");
                dto.setPassword(password);
                

                respuesta.add(dto);
            }
            
            rset.close();
            psta.close();
            
            
        } catch (Exception e) {
            logger.error("Erro a lista todos los alumnos ", e);
        }finally{
            try {
                if(conn != null){
                    conn.close();
                }
            } catch (Exception e) {
                logger.error("Erro al cerrar la conexion ", e);
            }
        }
        return respuesta;
    }

    public boolean agregarUsuario(AlumnosDTO usuario) {
        Connection conn = null;
        PreparedStatement psta = null;
        boolean consulta = false;
        
        try {
            conn = dataSource.getConnection();
            
            StringBuilder nombre = new StringBuilder();
            StringBuilder marcas = new StringBuilder();
            
            List<Object> params = new ArrayList<Object>(0);
                    
            boolean login = usuario.getLogin() !=null &&  usuario.getLogin().length() > 0;
            boolean password = usuario.getPassword() != null && usuario.getPassword().length() > 0;            
            
            
            if(login && password){
                params.add(usuario.getLogin());
                params.add(usuario.getPassword());
                
                
                
                
                String insert = AlumnosDTO.getInsert(nombre, marcas);
                psta = conn.prepareStatement(insert);
                
                logger.info("Ejecutando el insert: " + insert);
                
                int i = 1;
                for(Object param : params){
                    if(param instanceof Integer){
                        psta.setInt(i, (Integer) param);
                    }
                    
                    if(param instanceof String){
                        psta.setString(i, (String) param);
                    }
                    
                    if(param instanceof java.util.Date){
                        Date fech =(Date) param;
                        psta.setDate(i, new java.sql.Date(fech.getTime()));
                    }
                    
                    if(param instanceof Long){
                       psta.setLong(i, (Long) param);
                    }
                    
                    i++;
                    
                }
                
                int result = psta.executeUpdate();
                
                if(result == 1){
                    consulta = true;
                }else{
                    consulta =  false;
                }                
                psta.close();
            }
            
        } catch (Exception e) {
            logger.error("Error al guardar usuario", e);
        }finally{
            try {
                if(conn != null){
                    conn.close();
                }
            } catch (Exception e) {
                logger.error("Error al cerrar la conexion", e);
            }
        }
        
        
        return consulta;
    }
    
    
    
}
